package com.is.add.task;


import com.is.add.enmus.MonitorUrlEnum;
import com.is.add.mapper.ServerListMapper;
import com.is.add.model.ServerList;
import com.is.add.model.ServerMonitor;
import com.is.add.service.MonitorService;
import com.is.add.util.PropertiesUtil;
import com.is.add.util.SMSManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import sun.net.www.protocol.http.HttpURLConnection;
import tk.mybatis.mapper.entity.Example;

import java.io.IOException;
import java.net.URL;
import java.util.Date;
import java.util.List;
import java.util.Properties;


/**
 * 定时任务
 */
@Component
public class CronJob {
    @Autowired
    private MonitorService monitorService;
    @Autowired
    private ServerListMapper serverListMapper;
    int montitorTimes=0;
    /**
     * 每隔5分钟查询一次服务器链接，保存服务器状态
     */
    @Scheduled(cron = "0 */15 * * * * ")   //每十五分钟执行一次
    public void monitorServerStatus(){
        montitorTimes++;
        Example serverExample = new Example(ServerList.class);
        serverExample.createCriteria().andEqualTo("hasMonitor",true);
        List<ServerList> serverLists = this.serverListMapper.selectByExample(serverExample);
        for (ServerList v: serverLists) {
            ServerMonitor serverMonitor = new ServerMonitor();
            serverMonitor.setServerId(v.getId().intValue());
            serverMonitor.setServerName(v.getServerName());
            serverMonitor.setMonitorTime(new Date());
            serverMonitor = checkUrl(serverMonitor,v.getServerUrl());
            if (serverMonitor.getServerStatus().equals("FAILURE")){
                for (int i = 0; i < 3;i ++){
                    ServerMonitor sm = checkUrl(serverMonitor,v.getServerUrl());
                    if (sm.getServerStatus().equals("SUCCESS")){
                        serverMonitor.setServerStatus("SUCCESS");
                        break;
                    }
                }
            }
            if (serverMonitor.getServerStatus().equals("FAILURE")) {
                String msg = "警告！警告！" +serverMonitor.getServerName() + "发生异常，请即使处理。";
                Properties prop = PropertiesUtil.getProperties("src/manger.properties");
                for (String key : prop.stringPropertyNames()) {
                    SMSManager.send(key, msg);
                }
            }
            this.monitorService.save(serverMonitor);
        }
        System.out.println("服务器监控扫描"+montitorTimes+"次");
    }

    private ServerMonitor checkUrl(ServerMonitor serverMonitor,String serverUrl){
        try {
            URL url = new URL(serverUrl);
            HttpURLConnection urlCon = (HttpURLConnection)url.openConnection();
            urlCon.setConnectTimeout(8000);             //设置连接主机超时（单位：毫秒）
            urlCon.setReadTimeout(8000);                //设置从主机读取数据超时（单位：毫秒）
            urlCon.connect();                           //获取连接
            if (urlCon.getResponseCode() == 200){
                serverMonitor.setServerStatus("SUCCESS");
            }else {
                serverMonitor.setServerStatus("FAILURE");
            }
            serverMonitor.setMonitorResultMessage(urlCon.getResponseMessage());
        } catch (IOException e) {
            serverMonitor.setServerStatus("FAILURE");
            serverMonitor.setMonitorResultMessage(e.getMessage());
            e.printStackTrace();
        }
        return serverMonitor;
    }
}
